const pool = require('../tools/getPool');
const sendResponse = require('../tools/sendResponse');

module.exports = function(req, res){

	let name = req.body.name;
	let able = req.body.able;

	pool.getConnection(function(err, connection) {
		if (err) { 
			sendResponse('error','database error', null, res);
			return;
		}
		let params = [];

		if (name != undefined) {

			if (able == 1) {
				name = "%" + name + "%";
				sql = 'SELECT * FROM medicine WHERE able = 1 and name LIKE ?';
				params = [name];
			} else {
				name = "%" + name + "%";
				sql = 'SELECT * FROM medicine WHERE able = 1 and name LIKE ?';
				params = [name];
			}

		} else {
			if (able == 1) {
				sql = 'SELECT * FROM medicine WHERE able = 1';
				params = [];
			} else {
				sql = 'SELECT * FROM medicine';
				params = [];
			}
		}

		connection.query(sql, params, function (error, rows, fields) {

			connection.release();

			if (error) { 
				sendResponse('error','database error', null, res);
			} else {
				let result = {
					data: rows
				}
				sendResponse('ok','success', result, res);
			}
			return ;
		})	

	});

}